#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化的用户管理API
"""

import json
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.core.database import get_db
from app.models.permission_simple import User, Role
from pydantic import BaseModel, Field
from fastapi import HTTPException

router = APIRouter()

# 请求模型
class UserCreate(BaseModel):
    username: str = Field(..., min_length=3, max_length=50)
    name: str = Field(..., min_length=2, max_length=100)
    password: str = Field(..., min_length=6, max_length=50)
    role_id: int
    is_active: bool = True

class UserUpdate(BaseModel):
    name: str = Field(..., min_length=2, max_length=100)
    role_id: int
    is_active: bool = True

class UserResponse(BaseModel):
    id: int
    username: str
    name: str
    role_id: int
    role_name: str
    is_active: bool
    created_at: str

class RoleCreate(BaseModel):
    name: str = Field(..., min_length=2, max_length=50)
    menu_permissions: List[str] = []
    is_active: bool = True

class RoleUpdate(BaseModel):
    name: str = Field(..., min_length=2, max_length=50)
    menu_permissions: List[str] = []
    is_active: bool = True

class RoleResponse(BaseModel):
    id: int
    name: str
    menu_permissions: List[str]
    is_active: bool
    created_at: str

# 菜单配置
MENU_CONFIG = [
    {"key": "monitor", "name": "监控中心", "path": "/monitor", "icon": "Monitor"},
    {"key": "streams", "name": "直播流管理", "path": "/streams", "icon": "VideoCamera"},
    {"key": "tasks", "name": "任务管理", "path": "/tasks", "icon": "List"},
    {"key": "clips", "name": "拆条任务", "path": "/clip-tasks", "icon": "Scissor"},
    {"key": "records", "name": "录制管理", "path": "/recordings", "icon": "VideoPlay"},
    {"key": "servers", "name": "集群管理", "path": "/servers", "icon": "Monitor"},
    {"key": "users", "name": "人员管理", "path": "/users", "icon": "User"},
    {"key": "storage", "name": "文件存储", "path": "/storage", "icon": "Folder"}
]

@router.get("/users/list")
async def get_users(db: Session = Depends(get_db)):
    """获取用户列表"""
    try:
        users = db.query(User).all()
        items = []
        for user in users:
            items.append({
                "id": user.id,
                "username": user.username,
                "name": user.name,
                "role_id": user.role_id,
                "role_name": user.role.name if user.role else None,
                "is_active": user.is_active,
                "created_at": user.created_at.isoformat() if user.created_at else None
            })
        return {
            "code": 200,
            "data": {
                "items": items,
                "total": len(items)
            },
            "message": "success"
        }
    except Exception as e:
        import traceback
        print("错误:", traceback.format_exc())
        return {
            "code": 500,
            "data": None,
            "message": str(e)
        }

@router.post("/users")
async def create_user(user: UserCreate, db: Session = Depends(get_db)):
    """创建用户"""
    # 检查用户名是否已存在
    if db.query(User).filter(User.username == user.username).first():
        raise HTTPException(status_code=400, detail="用户名已存在")
    
    # 检查角色是否存在
    role = db.query(Role).filter(Role.id == user.role_id).first()
    if not role:
        raise HTTPException(status_code=400, detail="角色不存在")
    
    from app.services.auth import get_password_hash
    
    db_user = User(
        username=user.username,
        name=user.name,
        password=get_password_hash(user.password),
        role_id=user.role_id,
        is_active=user.is_active
    )
    
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    
    return {
        "code": 200,
        "message": "用户创建成功",
        "data": db_user.to_dict()
    }

@router.put("/users/{user_id}")
async def update_user(user_id: int, user: UserUpdate, db: Session = Depends(get_db)):
    """更新用户"""
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 检查角色是否存在
    role = db.query(Role).filter(Role.id == user.role_id).first()
    if not role:
        raise HTTPException(status_code=400, detail="角色不存在")
    
    db_user.name = user.name
    db_user.role_id = user.role_id
    db_user.is_active = user.is_active
    
    db.commit()
    db.refresh(db_user)
    
    return {
        "code": 200,
        "message": "用户更新成功",
        "data": db_user.to_dict()
    }

@router.delete("/users/{user_id}")
async def delete_user(user_id: int, db: Session = Depends(get_db)):
    """删除用户"""
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    db.delete(db_user)
    db.commit()
    
    return {"message": "用户删除成功"}

@router.get("/roles/list")
async def get_roles(db: Session = Depends(get_db)):
    """获取角色列表"""
    try:
        roles = db.query(Role).all()
        items = []
        for role in roles:
            # 将逗号分隔的字符串转换为列表
            if role.menu_permissions:
                menu_permissions = [p.strip() for p in str(role.menu_permissions).split(',') if p.strip()]
            else:
                menu_permissions = []
            
            items.append({
                "id": role.id,
                "name": role.name,
                "menu_permissions": menu_permissions,
                "is_active": role.is_active,
                "created_at": role.created_at.isoformat() if role.created_at else None
            })
        return {
            "code": 200,
            "data": {
                "items": items,
                "total": len(items)
            },
            "message": "success"
        }
    except Exception as e:
        import traceback
        print("错误:", traceback.format_exc())
        return {
            "code": 500,
            "data": None,
            "message": str(e)
        }

@router.post("/roles")
async def create_role(role: RoleCreate, db: Session = Depends(get_db)):
    """创建角色"""
    # 检查角色名称是否已存在
    if db.query(Role).filter(Role.name == role.name).first():
        raise HTTPException(status_code=400, detail="角色名称已存在")
    
    db_role = Role(
        name=role.name,
        menu_permissions=','.join(role.menu_permissions),
        is_active=role.is_active
    )
    
    db.add(db_role)
    db.commit()
    db.refresh(db_role)
    
    return {
        "code": 200,
        "message": "角色创建成功",
        "data": db_role.to_dict()
    }

@router.put("/roles/{role_id}")
async def update_role(role_id: int, role: RoleUpdate, db: Session = Depends(get_db)):
    """更新角色"""
    db_role = db.query(Role).filter(Role.id == role_id).first()
    if not db_role:
        raise HTTPException(status_code=404, detail="角色不存在")
    
    # 检查角色名称是否重复
    existing = db.query(Role).filter(Role.name == role.name, Role.id != role_id).first()
    if existing:
        raise HTTPException(status_code=400, detail="角色名称已存在")
    
    db_role.name = role.name
    db_role.menu_permissions = ','.join(role.menu_permissions)
    db_role.is_active = role.is_active
    
    db.commit()
    db.refresh(db_role)
    
    return {
        "code": 200,
        "message": "角色更新成功",
        "data": db_role.to_dict()
    }

@router.delete("/roles/{role_id}")
async def delete_role(role_id: int, db: Session = Depends(get_db)):
    """删除角色"""
    db_role = db.query(Role).filter(Role.id == role_id).first()
    if not db_role:
        raise HTTPException(status_code=404, detail="角色不存在")
    
    # 检查是否有用户在使用这个角色
    user_count = db.query(User).filter(User.role_id == role_id).count()
    if user_count > 0:
        raise HTTPException(status_code=400, detail="该角色正在被用户使用，无法删除")
    
    db.delete(db_role)
    db.commit()
    
    return {"message": "角色删除成功"}

@router.get("/menus")
async def get_menus():
    """获取菜单配置"""
    return MENU_CONFIG

@router.get("/user/menus")
async def get_user_menus(current_user_id: int = Depends(lambda: 1), db: Session = Depends(get_db)):
    """获取当前用户的菜单权限"""
    user = db.query(User).filter(User.id == current_user_id).first()
    if not user or not user.role:
        return []
    
    return [menu for menu in MENU_CONFIG if menu["key"] in user.role.menu_permissions]